package com.wn.base;

import java.io.*;
import java.util.Arrays;

/**
 * @FileName: DataFilterUtil
 * @Description: 将oracle insert语句转换为mysql insert语句
 * @Author: MaWenHao
 * @Created: 2020/12/15 - 16:51
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class DataFilterUtil {

    public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
        File file = new File("data/");
        File[] files = file.listFiles();
        Arrays.stream(files)
                .filter(DataFilterUtil::filterSqlFile)
                .forEach(DataFilterUtil::convert);
    }

    private static void convert(File file) {
        String originalName = file.getAbsolutePath();
        int index = originalName.lastIndexOf(".");
        StringBuilder sb = new StringBuilder();
        sb.append(originalName.substring(0, index))
                .append("_mysql")
                .append(originalName.substring(index, originalName.length()));
        String newFileName = sb.toString();
        try (
                BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFileName), "UTF-8"))
        ) {
            bw.write("truncate table " + file.getName().substring(0, index));
            int n = 0;
            String line;
            while ((line = br.readLine()) != null) {
                if (n < 3) {
                    n++;
                    continue;
                }
                if (line.startsWith("prompt ")) {
                    continue;
                }
                String newLine = line.replace("to_date", "str_to_date")
                        .replace("hh24:mi:ss", "%H:%d:%s")
                        .replace("dd-mm-yyyy", "%d-%m-%Y");
                bw.write(newLine);
                bw.newLine();
            }
            bw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static boolean filterSqlFile(File file) {
        if (null == file || file.isDirectory() || !file.getName().endsWith(".sql")) {
            return false;
        }
        return true;
    }
}


